package com.whu.exam.modules.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whu.exam.core.exception.ServiceException;
import com.whu.exam.modules.exam.entity.ExamClassno;
import com.whu.exam.modules.exam.mapper.ExamClassnoMapper;
import com.whu.exam.modules.exam.service.ExamClassnoService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ExamClassnoServiceImpl extends ServiceImpl<ExamClassnoMapper, ExamClassno> implements ExamClassnoService {

    @Override
    public void saveAll(String examId, List<String> classnos) {

        // 先删除
        QueryWrapper<ExamClassno> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ExamClassno::getExamId, examId);
        this.remove(wrapper);

        // 再增加
        if(CollectionUtils.isEmpty(classnos)){
            throw new ServiceException(1, "请至少选择选择一个班级！！");
        }
        List<ExamClassno> list = new ArrayList<>();

        for(String id: classnos){
            ExamClassno classno = new ExamClassno();
            classno.setClassnoId(id);
            classno.setExamId(examId);
            list.add(classno);
        }

        this.saveBatch(list);
    }

    @Override
    public List<String> listByExam(String examId) {
        // 先删除
        QueryWrapper<ExamClassno> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ExamClassno::getExamId, examId);
        List<ExamClassno> list = this.list(wrapper);
        List<String> ids = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            for(ExamClassno item: list){
                ids.add(item.getClassnoId());
            }
        }

        return ids;

    }
}
